package com.imc.core.aop;

import com.imc.core.annotation.Logs;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by tanweiping on 2018/7/24.
 */
@Slf4j
@Aspect
@Order(0)
@Component
public class WebLogHandler {

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("@annotation(webLog)")
    public void Logs(Logs webLog){}

    // add,update,query,del
//    @Pointcut("execution(* com.imc.core.rest..*.*(..))")
//    public void restWebLog(){}


    @Before("Logs(webLog)")
    public void doBefore(JoinPoint joinPoint,Logs webLog) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 省略日志记录内容
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "Logs(webLog)")
    public void doAfterReturning(Object ret,Logs webLog) throws Throwable {
// 处理完请求，返回内容
        log.info("RESPONSE : " + ret);
        long time = (System.currentTimeMillis() - startTime.get());
        if (time>3000){
            log.error("SPEND TIME : " + time);
        }else {
            log.info("SPEND TIME : " + time);
        }

    }


}
